from flask import Flask
from sqllite import Sqlite
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
admin = Admin(app, name='后台管理页面')
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mssql+pymssql://sa:saftop@localhost/171219?charset=cp936'
db = SQLAlchemy(app)


# home page
@app.route('/')
def test():
    return 'welcome to home page!'


# 自定义网页
class MyView(BaseView):
    @expose('/')
    def index(self):
        return self.render('index.html')


# 数据库模型视图
class UserView(ModelView):
    # 这三个变量定义管理员是否可以增删改，默认为True
    can_delete = False
    can_edit = False
    # can_create = False
    # 这里是为了自定义显示的column名字
    column_labels = dict(name=u'用户名', )
    # 如果不想显示某些字段，可以重载这个变量
    column_exclude_list = ('password_hash', )


class User(db.Model):
    __tablename__ = 'acscon_user'  # 映射的数据库表名
    id = db.Column(db.String(40), primary_key=True)
    usercode = db.Column(db.String(100), unique=True)
    name = db.Column(db.String(80), unique=False, nullable=False)
    sex = db.Column(db.Integer, unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username


admin.add_view(MyView(name=u'Hello'))
# 只需把自己写的处理模型的视图加进去就行了，category是可选的目录
admin.add_view(UserView(User, db.session, name='用户管理'))

if __name__ == '__main__':
    # Sqlite().execute('delete from user')
    # Sqlite().execute('insert into user(id,name,age) values (5,"张三",10)')
    # Sqlite().execute('insert into user(id,name,age) values (6,"李四",12)')
    # Sqlite().execute('insert into user(id,name,age) values (7,"王五",14)')
    # Sqlite().execute('insert into user(id,name,age) values (8,"赵六",15)')
    app.run(port=6003, host='0.0.0.0')
